<div class="content">
    {% if team_assignment %}
        <h1>Unassigned Team PDF Uploads (Please Enter the User Id of One Team Member)</h1>
    {% else %}
        <h1>Unassigned PDF Uploads</h1>
    {% endif %}

    <div style="text-align:center;margin:10px;padding:5px;">
        <button type="button" id="bulk_submit_all" class="btn btn-primary" onclick="submitAll(1)">Submit All Uploaded PDFS</button>
        <button type="button" id="bulk_delete_all" class="btn btn-default" onclick="confirmDeleteAll()">Delete All Uploaded PDFS</button>
    </div>

    <table class="table table-striped table-bordered persist-area">
        <thead>
        <tr>
            <td width="3%"></td>
            <td width="8%">Timestamp</td>
            <td width="53%">PDF preview</td>
            <td width="5%">Full PDF</td>
            <td width="15%">User ID</td>
            <td>Page Count</td>
            <td width="8%">Submit</td>
            <td width="8%">Delete</td>
        </tr>
        </thead>
        <tbody>
            {% for file in files %}
                {% if file["valid"] == false %}
                    <tr class="tr tr-vertically-centered" style="background-color:pink;" id="row-{{ loop.index}}">
                {% else %}
                    <tr class="tr tr-vertically-centered" id="row-{{ loop.index }}" >
                {% endif %}
                    <td>{{ loop.index }}</td>
                    <td>{{ file.clean_timestamp }}</td>
                    <td>
                        {{ file.filename_full }}
                        <br>
                        <div class="scrollable-image" >
                            <img src="{{ file.cover_image.url }}" width="100%" alt = "{{ file.filename_full }} preview"/>
                        </div>
                    </td>
                    <td>
                        <a href="javascript:openFile('{{ file.url_full }}');" aria-label="View full PDF in a new window">
                            <i class="fas fa-window-restore"></i>
			            </a>
                    </td>
                    <td id="input_area">
                        <input type="hidden" name="csrf_token" value="{{ csrf_token }}"/>
                        <div id="users_{{ loop.index }}">
                            <input type="text" id="bulk_user_id_{{ loop.index }}" aria-label = "Enter User ID to assign"
                                value ="{{ file["id"] }}"
                                {# we should only submit on enter for normal bulk uploads or on the last team upload box #}
                                {% if not team_assignment %}
                                    onkeydown="uploadOnEnter( {{ loop.index }}, event );"
                                {% else %}
                                    onkeydown="focusNextOnEnter({{ loop.index }}, 0)"
                                {% endif %}
                            />
                            {% if team_assignment %}
                                {# (size - 1) because twig loops are range inclusive #}
                                {% set outer_loop = loop %}
                                {% for i in 1..(max_team_size - 1) %}
                                    <input type="text" id="bulk_user_id_{{ outer_loop.index }}[{{ i }}]" value =""
                                        {# if this is the last input box submit on enter, otherwise move to next box#}
                                        {% if i == (max_team_size - 1) %}
                                            onkeydown="uploadOnEnter({{ outer_loop.index }}, event);"
                                        {% else %}
                                            onkeydown="focusNextOnEnter({{ outer_loop.index}}, {{ i }} )"
                                        {% endif %}
                                    />
                                {% endfor %}
                            {% endif %}
                        </div>
                    </td>
                    <td class="pdf_page_count" id="page_count_{{ loop.index }}">
                        {{ file["page_count"] }}
                    </td>
                    <td>
                        <button type="button" id="bulk_submit_{{ loop.index }}" class="btn btn-primary"
                        onclick="uploadSplit( {{ loop.index }} )">Submit</button>
                    </td>
                    <td>
                        <button type="button" id="bulk_delete_{{ loop.index }}" class="btn btn-default" onclick="deleteSplit({{ loop.index }})">Delete</button>
                    </td>
                </tr>
            {% endfor %}
        </tbody>
    </table>
</div>

<script type="text/javascript">
    var path_list = {{ count_array|json_encode|raw }};
    var num_submissions = {{ files|length }};
    var CSRF = "{{ csrf_token }}";
    var g_id = "{{ gradeable_id }}";
    var max_team_size = {{ max_team_size }};
    //team_assignment may either be 1 or not given so convert to a string to handle either case
    var is_team_assignment = "{{ team_assignment }}" === "1";
    //autofill data
    $(function(){
        $("#messages").empty();
        if(sessionStorage.getItem("expected_count")){
            document.getElementById("expected-pages-input").value = sessionStorage.getItem("expected_count");
        }

        $("td > div :text").autocomplete({
            source: students_full
        });
        highlightPageCount();
    });

    window.addEventListener('onbeforeunload', function(e) {
        $("#messages").empty();
    });

    //gets the raw value entered in the expected page box
    function getExpectedPageBoxVal(){
        var expected_count_box = document.getElementById("expected-pages-input");
        if (!expected_count_box){
            return NaN;
        }

        return expected_count_box.value;
    }

    //parses the expected page box and returns a list of expected pages
    //accepts multiple pages and also ranges, e.g 1-5,8,8-13
    function parseExpectedPageBox(){
        var expected_count = getExpectedPageBoxVal();
        if ( isNaN(expected_count) || expected_count === "" || expected_count === null){
            return NaN;
        }

        parts = expected_count.split(',');
        ret = [];

        for (var i = 0; i < parts.length; i++) {
            if(parts[i].length > 1 && parts[i].includes('-')){
                //handle range
                tmp = parts[i].split('-');
                if (tmp.length != 2){ 
                    continue;
                }

                start = parseInt(tmp[0]);
                end = parseInt(tmp[1]);

                if (isNaN(start) || isNaN(end) || start < 0 || end < start){
                    continue;
                }

                for(var j = start; j <= end; j++){
                    ret.push(j);
                }

            }else{
                val = parseInt(parts[i]);
                if (isNaN(val) || val < 0){
                    continue;
                }

                ret.push( val );
            }
        }

        return ret;
    }

    //highlight pages that don't match the expected, also save the expected page count in session storage
    function highlightPageCount(){

        expected_count = parseExpectedPageBox();

        if (expected_count === [] || isNaN(expected_count) ){
            return;
        }

        var pages = document.getElementsByClassName("pdf_page_count");
        for (var i = pages.length - 1; i >= 0; i--) {
            if(expected_count.indexOf( parseInt(pages[i].innerHTML) ) === -1 ){
                pages[i].style.backgroundColor = "#FF5722";
            }else{
                pages[i].style.backgroundColor = "";
            }
        }

        //use the raw value entered by the user to prevent a conversion, e.g
        //we don't want to store 1-3 as 1,2,3
        sessionStorage.setItem("expected_count", getExpectedPageBoxVal());
    }

    function toggleButtons(index, disable){
        var submit_btn = document.getElementById("bulk_submit_" + String(index));
        var delete_btn = document.getElementById("bulk_delete_" + String(index));
        var user_id_textarea = document.getElementById("bulk_user_id_" + String(index));

        if(!submit_btn || !delete_btn || !user_id_textarea){
            return;
        }

        submit_btn.disabled = disable;
        delete_btn.disabled = disable;
        user_id_textarea.disabled = disable;

        if(is_team_assignment){
            for(var i = 1; i < max_team_size; i++){
                document.getElementById("bulk_user_id_" + String(index) + "[" + String(i) + "]").disabled = disable;
            }
        }
    }

    function moveToNextSubmission(index){
        let current = document.getElementById('row-' + String(index));
        if( current ){
            document.getElementById('row-' + String(index)).remove();
            num_submissions -= 1;
        }
        let next = document.getElementById("bulk_user_id_" + String(index + 1));
        if( next ){
            document.getElementById("bulk_user_id_" + String(index + 1)).focus();
        }
    }

    //if the user presses 'enter' try and make a submission as if hitting the submit button
    function uploadOnEnter(index, e = null){
        key = window.event ? window.event.keyCode : e.keyCode;
        if(key === 13){
            uploadSplit(index);
        }
    }

    //on enter move focus on the next submission box in a given row
    function focusNextOnEnter(table_row, input_index, e = null ){
        var key = window.event ? window.event.keyCode : e.keyCode;
        if(key !== 13){
            return;
        }
        var input_box  = document.getElementById("bulk_user_id_" + String(table_row) + "[" + String(input_index + 1) + "]" );
        if(!input_box){
            return;
        }

        input_box.focus();
    }

    function uploadSplit(index){
        var submit_btn = document.getElementById("bulk_submit_" + String(index));
        var delete_btn = document.getElementById("bulk_delete_" + String(index));
        var user_id_textarea = document.getElementById("bulk_user_id_" + String(index));

        if(is_team_assignment){
            var user_id = [];
            var tmp_user = document.getElementById("bulk_user_id_" + String(index)).value;
            if(tmp_user != ""){
                user_id.push(tmp_user);
            }

            for (var i = 1; i < max_team_size; i++) {
                tmp_user = document.getElementById("bulk_user_id_" + String(index) + "[" + String(i) + "]").value;
                if(tmp_user != ""){
                    user_id.push(tmp_user);
                }
            }
        }
        else {
            var user_id = user_id_textarea.value;
        }

        toggleButtons(index, true);
        var path = decodeURIComponent(path_list[index]);

        //verify user id is valid, then assign
        validateUserId(CSRF, g_id, user_id)
        .then(function(response){
            if(response['data']['previous_submission'] === false) {
                //no previous submission, submit split item normally
                uploadSplitHelper(user_id,path, index);
            }
            else {
                //user_id has previous submission give options to user first
                let has_been_called = false;
                var option = displayPreviousSubmissionOptions(getSubmissionOption);

                return;

                //callback function once user actually picks something
                function getSubmissionOption(option){
                    if(has_been_called){
                        return;
                    }

                    has_been_called = true;
                    //user closes do nothing
                    if(option === -1){
                        toggleButtons(index, false);
                        //if the user does nothing focus back on the first box or the last team box
                        if(is_team_assignment){
                            document.getElementById("bulk_user_id_" + String(index) + "[" + String(max_team_size-1) + "]").focus();
                        }
                        else{
                            user_id_textarea.focus();
                        }
                        return;
                    }

                    var merge_previous = false;
                    var clobber = false;

                    if(option == 2){
                        merge_previous = true;
                    }
                    else if(option == 3){
                        merge_previous = true;
                        clobber = true;
                    }
                    uploadSplitHelper(user_id,path,index,merge_previous,clobber);
                }
            }
        })
        .catch(function(response){
            //allow user to retry assigning on failure
            toggleButtons(index, false);
            console.error(response);
            displaySubmissionMessage(response);
        });
    }

    function uploadSplitHelper(user_id,path,index = 0,merge_previous = false,clobber = false){
        submitSplitItem(CSRF, g_id, user_id, path, merge_previous, clobber)
        .then(function(submit_response){
            displaySubmissionMessage(submit_response);
            moveToNextSubmission(index);
        })
        .catch(function(submit_response){
            displaySubmissionMessage(submit_response);
            console.error(submit_response);
            //allow user to retry assigning on failure
            toggleButtons(index, false);
        });
    }

    function deleteSplit(index){
        var submit_btn = document.getElementById("bulk_submit_" + String(index));
        var delete_btn = document.getElementById("bulk_delete_" + String(index));
        var user_id_textarea = document.getElementById("bulk_user_id_" + String(index));

        toggleButtons(index, true);

        var path = decodeURIComponent(path_list[index]);

        //delete split item after confirm
        if(confirm("Are you sure you want to delete this submission?")){
            deleteSplitItem(CSRF,g_id,path)
            .then(function(submit_response){
                displaySubmissionMessage(submit_response);
                moveToNextSubmission(index);
            })
            .catch(function(submit_response){
                console.error(submit_response);
                displaySubmissionMessage(submit_response);

                toggleButtons(index, false);
            });
        }
        else{
            //enable submit options if we don't delete
            toggleButtons(index, false);
        }
    }

    function submitAll(index){
        if(index > Object.keys(path_list).length){
            return;
        }

        var text_area = document.getElementById("bulk_user_id_" + String(index));
        var expected_count = parseExpectedPageBox();

        var user_id = "";
        if(text_area !== null){
            if(text_area.disabled === false){
                user_id = text_area.value;
            }
            else{
                return submitAll(index + 1);
            }
        }
        else{
            return submitAll(index + 1);
        }
        //if the expected page count doesn't match skip and let the user decide
        var page_count = document.getElementById("page_count_" + String(index));
        if(page_count && expected_count !== [] && !isNaN(expected_count) ){
            if(expected_count.indexOf(parseInt(page_count.innerHTML) ) === -1 ){
                return submitAll(index + 1);
            }
        }

        //if theres an invalid submission skip this
        if(document.getElementById("row-" + String(index)).style.backgroundColor == "pink"){
            return submitAll(index + 1);
        }

        var path = decodeURIComponent(path_list[index]);

        validateUserId(CSRF,g_id,user_id)
        .then(function(response){
            if(response['data']['previous_submission'] === false){
                var submit_btn = document.getElementById("bulk_submit_" + String(index));
                var delete_btn = document.getElementById("bulk_delete_" + String(index));
                var user_id_textarea = document.getElementById("bulk_user_id_" + String(index));

                moveToNextSubmission(index);
                uploadSplitHelper(user_id,path,index);
                return submitAll(index + 1);
            }
            else{
                return submitAll(index + 1);
            }
        })
        .catch(function(response){
            displaySubmissionMessage(response);
            console.error(response);
            return submitAll(index + 1);
        });
    }

    function confirmDeleteAll(){
        if(confirm("Are you sure you want to delete " + String(num_submissions) + " submissions?")){
            deleteAll(1);
        }
    }

    function deleteAll(index){
        if(index > Object.keys(path_list).length){
            return;
        }

        var submit_btn = document.getElementById("bulk_submit_" + String(index));
        var delete_btn = document.getElementById("bulk_delete_" + String(index));
        var user_id_textarea = document.getElementById("bulk_user_id_" + String(index));

        if(submit_btn === null){
            return deleteAll(index + 1);
        }
        else if(submit_btn.disabled === true){
            return deleteAll(index + 1);
        }
        var path = decodeURIComponent(path_list[index]);

        deleteSplitItem(CSRF,g_id,path)
        .then(function(submit_response){
            displaySubmissionMessage(submit_response);
            moveToNextSubmission(index);
            return deleteAll(index + 1);
        })
        .catch(function(submit_response){
            console.error(submit_response);
            displaySubmissionMessage(submit_response);

            toggleButtons(index, false);
            return deleteAll(index + 1);
        });
    }
</script>
